<template>
  <div class="favorites-container page-container">
    <h1 class="page-title">我的收藏</h1>
    
    <div v-if="userStore.loading" class="loading">
      <el-skeleton :rows="3" animated />
    </div>
    
    <div v-else-if="userStore.favorites.length === 0" class="no-favorites">
      <el-empty description="暂无收藏的城市" :image-size="150">
        <template #description>
          <p>您还没有收藏任何城市</p>
        </template>
        <el-button type="primary" @click="goToHome">去首页收藏</el-button>
      </el-empty>
    </div>
    
    <div v-else class="favorites-list">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" 
                v-for="(favorite, index) in userStore.favorites" 
                :key="index">
          <el-card class="favorite-card" shadow="hover">
            <div class="favorite-header">
              <h3>{{ favorite.city }}</h3>
              <p>{{ favorite.province }}</p>
            </div>
            
            <div v-if="cityWeatherMap[getCityKey(favorite)]" class="favorite-weather">
              <div class="weather-top">
                <div class="weather-icon">
                  <i v-if="cityWeatherMap[getCityKey(favorite)].icon" 
                     :class="`qi-${cityWeatherMap[getCityKey(favorite)].icon} qi-48`"></i>
                  <i v-else
                     :class="getWeatherIcon(cityWeatherMap[getCityKey(favorite)].weatherCondition) + ' qi-48'"></i>
                </div>
                <div class="weather-temp">
                  {{ cityWeatherMap[getCityKey(favorite)].temperature }}°C
                </div>
              </div>
              
              <div class="weather-info">
                <p>{{ cityWeatherMap[getCityKey(favorite)].text || cityWeatherMap[getCityKey(favorite)].weatherCondition }}</p>
                <p>{{ cityWeatherMap[getCityKey(favorite)].temperatureLow }}°C ~ {{ cityWeatherMap[getCityKey(favorite)].temperatureHigh }}°C</p>
                <p>湿度: {{ cityWeatherMap[getCityKey(favorite)].humidity }}%</p>
                <p>风速: {{ cityWeatherMap[getCityKey(favorite)].windSpeed }} km/h</p>
              </div>
            </div>
            
            <div v-else class="weather-loading">
              <el-skeleton :rows="3" animated />
            </div>
            
            <div class="favorite-actions">
              <el-button 
                type="primary" 
                size="small" 
                @click="viewDetail(favorite)"
              >
                查看详情
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleRemoveFavorite(favorite)"
                :loading="favorite.removing"
              >
                取消收藏
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../store/user'
import { useWeatherStore } from '../store/weather'

// 路由
const router = useRouter()

// 状态管理
const userStore = useUserStore()
const weatherStore = useWeatherStore()

// 城市天气映射
const cityWeatherMap = reactive({})

// 初始化数据
onMounted(async () => {
  // 确保用户已登录
  if (!userStore.isAuthenticated) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  // 获取收藏城市列表
  try {
    await userStore.fetchFavorites()
    
    // 获取每个城市的天气信息
    await fetchAllFavoritesWeather()
  } catch (error) {
    ElMessage.error('获取收藏城市失败')
  }
})

// 获取所有收藏城市的天气
const fetchAllFavoritesWeather = async () => {
  if (!userStore.favorites || userStore.favorites.length === 0) return
  
  // 准备城市列表
  const cityList = userStore.favorites.map(favorite => ({
    city: favorite.city,
    province: favorite.province
  }))
  
  try {
    // 批量获取城市天气
    const response = await weatherStore.getMultiCityWeather(cityList)
    
    // 更新城市天气映射
    if (response && response.data && response.data.weather) {
      response.data.weather.forEach(weather => {
        const key = `${weather.city}:${weather.province}`
        cityWeatherMap[key] = weather
      })
    }
  } catch (error) {
    ElMessage.error('获取城市天气信息失败')
  }
}

// 获取城市唯一键
const getCityKey = (city) => {
  return `${city.city}:${city.province}`
}

// 查看详情
const viewDetail = (favorite) => {
  // 设置搜索表单并跳转到首页
  weatherStore.getCityWeather(favorite.city, favorite.province)
    .then(() => {
      router.push('/')
    })
    .catch(error => {
      ElMessage.error('获取城市天气失败')
    })
}

// 处理移除收藏
const handleRemoveFavorite = (favorite) => {
  ElMessageBox.confirm(
    `确定要取消收藏 ${favorite.city} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    // 设置正在删除状态
    favorite.removing = true
    
    try {
      await userStore.removeFavorite(favorite.city, favorite.province)
      ElMessage.success('已取消收藏')
    } catch (error) {
      ElMessage.error('取消收藏失败')
    } finally {
      favorite.removing = false
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 跳转到首页
const goToHome = () => {
  router.push('/')
}

// 根据天气状况获取图标
const getWeatherIcon = (condition, isNight = false) => {
  // 根据天气状况映射到和风天气图标代码
  const iconMap = {
    '晴': isNight ? 'qi-150' : 'qi-100',
    '多云': isNight ? 'qi-151' : 'qi-101',
    '少云': isNight ? 'qi-152' : 'qi-102',
    '晴间多云': isNight ? 'qi-153' : 'qi-103',
    '阴': 'qi-104',
    '阵雨': isNight ? 'qi-350' : 'qi-300',
    '强阵雨': isNight ? 'qi-351' : 'qi-301',
    '雷阵雨': 'qi-302',
    '强雷阵雨': 'qi-303',
    '雷阵雨伴有冰雹': 'qi-304',
    '小雨': 'qi-305',
    '中雨': 'qi-306',
    '大雨': 'qi-307',
    '极端降雨': 'qi-308',
    '毛毛雨': 'qi-309',
    '暴雨': 'qi-310',
    '大暴雨': 'qi-311',
    '特大暴雨': 'qi-312',
    '冻雨': 'qi-313',
    '小到中雨': 'qi-314',
    '中到大雨': 'qi-315',
    '大到暴雨': 'qi-316',
    '暴雨到大暴雨': 'qi-317',
    '大暴雨到特大暴雨': 'qi-318',
    '雨': 'qi-399',
    '小雪': 'qi-400',
    '中雪': 'qi-401',
    '大雪': 'qi-402',
    '暴雪': 'qi-403',
    '雨夹雪': 'qi-404',
    '雨雪天气': 'qi-405',
    '阵雨夹雪': isNight ? 'qi-456' : 'qi-406',
    '阵雪': isNight ? 'qi-457' : 'qi-407',
    '小到中雪': 'qi-408',
    '中到大雪': 'qi-409',
    '大到暴雪': 'qi-410',
    '雪': 'qi-499',
    '薄雾': 'qi-500',
    '雾': 'qi-501',
    '霾': 'qi-502',
    '扬沙': 'qi-503',
    '浮尘': 'qi-504',
    '沙尘暴': 'qi-507',
    '强沙尘暴': 'qi-508',
    '热': 'qi-900',
    '冷': 'qi-901',
    '未知': 'qi-999'
  }
  
  // 如果传入的是图标代码，直接使用
  if (condition && condition.startsWith('qi-')) {
    return condition
  }
  
  // 如果有传入icon属性，直接使用
  if (condition && condition.icon) {
    return `qi-${condition.icon}`
  }
  
  return iconMap[condition] || 'qi-999'
}
</script>

<style scoped>
.favorites-container {
  padding-top: 30px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.page-title {
  font-size: 24px;
  margin-bottom: 30px;
  color: #303133;
  text-align: center;
}

.no-favorites {
  margin-top: 50px;
}

.favorites-list {
  margin-bottom: 30px;
}

.favorite-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: transform 0.3s;
}

.favorite-card:hover {
  transform: translateY(-5px);
}

.favorite-header {
  margin-bottom: 15px;
}

.favorite-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.favorite-header p {
  margin: 5px 0 0;
  color: #909399;
  font-size: 14px;
}

.favorite-weather {
  margin-bottom: 15px;
}

.weather-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.weather-icon i {
  font-size: 40px;
  color: #409eff;
}

.weather-temp {
  font-size: 24px;
  font-weight: 600;
}

.weather-info p {
  margin: 5px 0;
  font-size: 14px;
  color: #606266;
}

.weather-loading {
  padding: 10px 0;
  margin-bottom: 15px;
}

.favorite-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.loading {
  padding: 20px;
}
</style> 